package com.example.response;

import lombok.Data;
import lombok.ToString;

import java.io.Serializable;


/**
 * @author Lexin Huang
 * @since 2.0
 */
@Data
@ToString
public class ApiResult<T> implements Serializable {

    /**
     * Status-code 状态码
     */
    private Integer code;

    /**
     * Status-msg 请求状态信息
     */
    private String msg;

    /**
     * Data 数据实体
     */
    private Object data;

    /**
     * 用于指定表示 data 指定类, 作用相当于标识, 防止 Object 直接通过赋值器传入
     * 由于实际使用需要进行继承, 不利于开发, 已经被舍弃
     */
    @Data
    public static class ApiData {
        private Object m = null;
    }


    public ApiResult() {
        setError(ErrorStatus.SERVER_ERROR);
    }

    private ApiResult(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public ApiResult(SuccessStatus status) {
        setSuccess(status);
    }

    private void setSuccess(SuccessStatus status) {
        setStatus(status.code, status.msg);
    }

    @Deprecated
    public void setError(ErrorStatus status) {
        setError(status, status.msg);
    }

    @Deprecated
    public void setError(ErrorStatus status, String msg) {
        setStatus(status.code, msg);
        this.data = null;
    }
    public void setError(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public void setSuccess(T data) {
        setStatus(SuccessStatus.SUCCESS.code, SuccessStatus.SUCCESS.msg);
        this.data = data;
    }

    public void setSuccess(T data,String msg) {
        setStatus(SuccessStatus.SUCCESS.code, msg);
        this.data = data;
    }


    private void setStatus(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    /**
     * 设置响应的状态信息, 不应当包含 data 的设置, 且此方法为 public
     * 推荐使用{@link #setSuccess(Object)} (ApiData)} 或 {@link #setError(ErrorStatus)} 及其重载形式
     * @param code 状态码
     * @param msg 状态信息
     * @param data 数据
     */
    @Deprecated
    public void setStatus(int code,String msg,T data){
        this.code = code;
        this.msg = msg;
        this.data = data;
    }


    @Deprecated
    public static ApiResult<ApiData> buildParamFormatErrorResponse(String msg) {
        return buildErrorResponse(ErrorStatus.PARAM_FORMAT_ERROR, msg);
    }

    @Deprecated
    public static ApiResult<ApiData> buildErrorResponse(ErrorStatus status) {
        return buildErrorResponse(status, status.msg);
    }

    @Deprecated
    public static ApiResult<ApiData> buildErrorResponse(ErrorStatus errorStatus, String message) {
        return new ApiResult<>(errorStatus.code, message, new ApiData());
    }

    public static ApiResult<ApiData> buildErrorResponse(Integer code, String msg) {
        return new ApiResult<>(code, msg, new ApiData());
    }

    public static ApiResult<ApiData> buildNonDataSuccessResponse(String msg) {
        return new ApiResult<>(SuccessStatus.SUCCESS.code, msg, new ApiData());
    }

}
